<!--
 * @Author: your name
 * @Date: 2021-03-18 19:16:15
 * @LastEditTime: 2021-04-23 21:28:13
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \guzheng\src\views\pages\4.1game-answer.vue
-->
<template>
  <div>
    <div class="content">
      <div class="question">
        <div class="btn">
          <el-button type="primary" @click="dialogVisible = true">开始答题</el-button>
        </div>
        <div>我的答题记录</div>
        <div class="empty" v-if="!myAnswerRecord.length">暂无记录</div>
        <el-timeline>
          <el-timeline-item
            v-for="(item, index) in myAnswerRecord"
            :key="index"
            :timestamp="item.createTime">
            {{item.score === 100 ? item.score+'分 挑战成功' : item.score+'分 再接再厉'}}
          </el-timeline-item>
        </el-timeline>
      </div>

      <div class="top-score">
        <div>排行榜</div>
        <div class="empty" v-if="!topList.length">暂无记录</div>
        <div class="top-list" v-for="(item, index) of topList" :key="index">
          <div class="user">
            <el-avatar :size="40">{{item.name.split('')[0].toUpperCase()}}</el-avatar>
            <div>{{item.name}}</div>
          </div>
          <div>{{item.score}}分</div>
        </div>
      </div>
    </div>

    <el-dialog
      :title="`第 ${currentNum+1} 题`"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <span>{{questionList[currentNum].question}}</span>
      <el-radio-group v-model="answer">
        <el-radio 
          v-for="(item,index) of questionList[currentNum].choice" 
          :key="index" 
          :label="index+1"
        >
          {{item}}
        </el-radio>
      </el-radio-group>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" type="primary" :disabled="!answer" @click="confirm()">确 定</el-button>
      </span>
    </el-dialog>

    <div class="middle"></div>
  </div>
</template>

<script>
export default {
  name: "game",
  data() {
    return {
      /**题目列表*/
      questionList: [],
      /**排行榜列表*/
      topList: [],
      /**我的答题记录*/
      myAnswerRecord: [],
      /**答题框显示与隐藏*/
      dialogVisible: false,
      /**当前题目序号*/
      currentNum: 0,
      /**用户选择的答案*/
      answer: '',
      /**排行榜对象 */
      res: {},
    };
  },
  computed: {
    // 根据邮箱获取用户名
    getUserName: function() {
      const email = this.$store.state.user.email;
      return email.split("@")[0];
    },
  },
  mounted() {
    this.getQuestionList();
    this.getTopList();
    this.getMyRecord();
  },
  methods: {
    /**随机获取10个问题 */
    getQuestionList() {
      this.$http.get('/api/getQuestion').then(({ data }) => {
        data.data.forEach((item) => {
          item.choice = JSON.parse(item.choice);
        })
        this.questionList = data.data.concat().sort((a, b) => {
          return Math.random() - 0.5;
        });
        this.questionList.length = 10;
      })
    },

    /**获取排行榜 */
    getTopList() {
      this.$http.get('/api/getTop').then(({ data }) => {
        this.topList = data.data;
      })
    },

    /**获取用户答题记录 */
    getMyRecord() {
      const name = this.getUserName;
      this.$http.get('/api/getMyRecord/' + name).then(({ data }) => {
        this.myAnswerRecord = data.data.reverse();
      })
    },

    confirm() {
      if (this.answer === this.questionList[this.currentNum].correct) {
        this.answer = '';
        this.dialogVisible = false;
        this.currentNum++;
        if (this.currentNum < this.questionList.length) {
          setTimeout(() => {this.dialogVisible = true}, 500);
        } else {
          // 记录用户答题分数
          this.postScore();
          this.dialogVisible = false;
          this.currentNum = 0;
          this.$alert('恭喜！答题挑战成功！', '提示', {
            confirmButtonText: '确定',
            type: 'success',
            callback: () => {
              // 刷新题目
              this.getQuestionList();
              this.getMyRecord();
              this.getTopList();
            }
          });
        }
      } else {
        // 记录用户答题分数
        this.postScore();
        // 清空数据
        this.answer = '';
        this.currentNum = 0;
        this.dialogVisible = false;
        this.$alert('答题错误，下次继续努力！', '提示', {
          confirmButtonText: '确定',
          type: 'warning',
          callback: () => {
            this.getQuestionList();
            this.getMyRecord();
          }
        });
      }
    },
    /**记录用户答题分数 */
    postScore() {
      this.res.name = this.getUserName;
      this.res.score = this.currentNum * 10;
      this.res.createTime = new Date().toLocaleString();
      this.$http.post('/api/addTop', this.res)
        .then(({ data }) => {
          console.log(data);
        })
    },

    handleClose(done) {
      this.$confirm('确认取消答题？')
        .then(_ => {
          this.currentNum = 0;
          this.answer = '';
          done();
        })
        .catch(_ => {});
    }
  },
};
</script>

<style scoped>
.middle {
  height: 100%;
  width: calc(98% - 200px);
  background: url("../../assets/images/答题模块背景图.jpg") no-repeat center center;
  opacity: 0.2;
  position: absolute;
  top: 0;
  z-index: 0;
}
.btn {
  padding: 40px 0;
}
.content {
  position: relative;
  z-index: 99;
  display: flex;
}
.question {
  flex: 1 1;
}
.top-score {
  width: 220px;
  border-left: 1px solid #d7dae2;
}
.empty {
  color: #7b7b7b;
  padding: 20px 0;
}
.top-list {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px;
}
.top-list .user {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 10px 0;
  flex: 1 1;
}
::v-deep .el-dialog {
  text-align: left;
}
::v-deep .el-radio-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 20px;
}
::v-deep .el-timeline {
  text-align: left;
  display: flex;
  flex-direction: column;
  width: 150px;
  margin: 0 auto;
  padding: 20px 0;
}
</style>